/**   
 * @Title: ContractProtocoListService.java 
 * @Package com.betterjr.modules.contract.service 
 * @Description: 协议清单服务 
 * @author xuzx
 * @date 2017年10月26日 上午11:03:52  
 */
package com.betterjr.modules.contract.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.betterjr.common.service.BaseService;
import com.betterjr.common.utils.BTAssert;
import com.betterjr.common.utils.BetterDateUtils;
import com.betterjr.common.utils.BetterStringUtils;
import com.betterjr.common.utils.QueryTermBuilder;
import com.betterjr.common.utils.UserUtils;
import com.betterjr.mapper.pagehelper.Page;
import com.betterjr.modules.account.entity.CustOperatorInfo;
import com.betterjr.modules.account.service.CustOperatorService;
import com.betterjr.modules.contract.dao.ContractProtocolistMapper;
import com.betterjr.modules.contract.entity.ContractProtocolist;
import com.betterjr.modules.customer.ICustMechBaseService;
import com.betterjr.modules.document.ICustFileService;
import com.betterjr.modules.document.entity.CustFileItem;
import com.betterjr.modules.document.service.DataStoreService;

/** 
 * @ClassName: ContractProtocoListService 
 * @Description: 协议清单服务
 * @author xuzx
 * @date 2017年10月26日 上午11:03:52 
 *  
 */
@Service
public class ContractProtocoListService extends BaseService<ContractProtocolistMapper, ContractProtocolist> {

    @Reference(interfaceClass = ICustFileService.class)
    private ICustFileService custFileService;

    @Reference(interfaceClass = ICustMechBaseService.class)
    private ICustMechBaseService custMechBaseService;

    @Resource
    private ContractTemplateService contractTemplateService;

    @Resource
    private CustOperatorService custOperatorService;

    @Resource
    private ContractSignatoryService contractSignatoryService;

    @Resource
    private DataStoreService dataStoreService;

    @Resource
    private ContractTempStampPlaceService contractTempStampPlaceService;

    /**
     * 
     * @Title: saveContractProtocol 
     * @Description: 协议清档保存 
     * @param anMap  info参数
     * @param anRequestNo 业务单号
     * @param antemplateFileId 自定义上传文件编号
     * @param anCommonNo  签署方机构编号
     * @return 保存协议清单和签署方信息
     * @throws 
     * @author xuzx
     * @date 2017年10月31日 下午1:39:46
     */
    public ContractProtocolist saveContractProtocol(final Map<String, Object> anMap, final String anRequestNo,
            final String antemplateFileId, final String anCommonNo) {
        BTAssert.notNull(anRequestNo, "业务单号不能为空");
        final ContractProtocolist contractProtl = new ContractProtocolist();
        contractProtl.setRequestno(anRequestNo);
        contractProtl.initValue();
        // 根据上传编号保存上传编号，协议方式，自定义上传标记
        if (StringUtils.isNoneBlank(antemplateFileId)) {
            custFileService.updateCustFileItemInfo(antemplateFileId, null);
            contractProtl.setCustomTemplateId(Long.valueOf(antemplateFileId));
            contractProtl.setCustomTemplateName(custFileService.findOne(Long.valueOf(antemplateFileId)).getFileName());
            contractProtl.setCustomUpload("01");
            contractProtl.setProtocolName("自定义协议");
        } else {
            contractProtl.setCustomUpload("02");
            contractProtl.setProtocolName("预定义协议");
        }
        // 根据签署方信息编号插入签署方式
        String[] sourceStrArray = anCommonNo.split(",");
        if (sourceStrArray.length == 1) {
            contractProtl.setSignatoryMode("一方签署");
        } else {
            contractProtl.setSignatoryMode("多方签署");
        }
        // 保存清单相关信息
        contractProtl.setStandardTypeId(BetterStringUtils.toLong(anMap.get("standardTypeId")));
        contractProtl.setOriginalTemplateId(BetterStringUtils.toLong(anMap.get("templateId")));
        contractProtl.setStandardTypeName(String.valueOf(anMap.get("standardTypeName")));
        if (anMap.get("signatoryTheme") != null) {
            contractProtl.setSignatoryTheme(String.valueOf(anMap.get("signatoryTheme")));
        }
        if (anMap.get("themeEndDate") != null) {
            contractProtl.setThemeEndDate(BetterDateUtils.formatDispDate(String.valueOf(anMap.get("themeEndDate"))));
        }
        if (anMap.get("description") != null) {
            contractProtl.setDescription(String.valueOf(anMap.get("description")));
        }
        final Long contractProtlId = contractProtl.getId();
        // 保存签署方信息，对应参数机构编号，业务单号，协议编号
        contractSignatoryService.addContractSignatory(anCommonNo, anRequestNo, contractProtlId);
        final int result = this.insert(contractProtl);
        BTAssert.isTrue(result == 1, "协议清单保存失败！");
        return contractProtl;

    }

    /**
     * 
     * @Title: queryContractProtocolist 
     * @Description: 查询清单信息
     * @param anRequestNo 业务编号
     * @param anFlag  是否统计总计
     * @param anPageNum 页码
     * @param anPageSize 页面大小
     * @return 查询清单
     * @throws 
     * @author xuzx
     * @date 2017年10月31日 下午1:41:05
     */
    public Page<ContractProtocolist> queryContractProtocolist(final String anRequestNo, final int anFlag,
            final int anPageNum, final int anPageSize) {
        BTAssert.notNull(anRequestNo, "业务单号不能为空");
        Map<String, Object> anMap = QueryTermBuilder.newInstance().build();
        anMap.put("requestno", anRequestNo);
        return this.selectPropertyByPage(anMap, anPageSize, anPageNum, anFlag == 1);

    }

    /**
     * 
     * @Title: delContractProtocol 
     * @Description: 删除协议清单和关联签署信息
     * @param anId   协议清单id
     * @return 删除协议
     * @throws 
     * @author xuzx
     * @date 2017年10月31日 下午1:42:57
     */
    public int delContractProtocol(final Long anId) {
        BTAssert.notNull(anId, "协议清单编号不能为空");
        // 删除关联签署方信息
        contractSignatoryService.delAssociatedSignature(anId);
        // 删除关联签章位置
        contractTempStampPlaceService.delAssociatedLocation(anId);
        return this.deleteByPrimaryKey(anId);

    }

    /**
     * 
     * @Title: webQueryInformation 
     * @Description: 查询机构信息 
     * @param anCommonNo 机构编号
     * @return 机构信息
     * @throws 
     * @author xuzx
     * @date 2017年10月31日 下午1:44:14
     */
    public CustOperatorInfo webQueryInformation(final Long anCommonNo) {
        return custOperatorService.findDefaultOperator(custMechBaseService.findBaseInfo(anCommonNo).getOperOrg());

    }

    /**
     * 
     * @Title: webqueryContractProtocolist 
     * @Description: 根据清单编号查询详细信息 
     * @param anId 清单编号
     * @return 根据清单编号查询详细信息 
     * @throws 
     * @author xuzx
     * @date 2017年10月31日 下午4:37:39
     */
    public ContractProtocolist webqueryContractProtocolist(final Long anId) {
        BTAssert.notNull(anId, "协议清单编号不能为空");
        return this.selectByPrimaryKey(anId);

    }

    /**
     * 
     * @Title: updateContractProtocol 
     * @Description: 更新清单协议详情 
     * @param anId  协议清单编号
     * @return 更新清单协议详情 
     * @throws 
     * @author xuzx
     * @date 2017年10月31日 下午5:05:04
     */
    public ContractProtocolist updateContractProtocol(final Map<String, Object> anParam, final Long anId,
            final String anCustomTemplateId, final String anCommonNo) {
        final ContractProtocolist contractProtocolist = this.selectByPrimaryKey(anId);
        contractProtocolist.modifyValue();
        contractProtocolist.setStandardTypeId(BetterStringUtils.toLong(anParam.get("standardTypeId")));
        contractProtocolist.setOriginalTemplateId(BetterStringUtils.toLong(anParam.get("templateId")));
        final Long beforeUploadId = contractProtocolist.getCustomTemplateId();
        final Long afterUploadId = BetterStringUtils.toLong(anParam.get("customTemplate"));
        // 之前已存自定义文件，现在修改为其他自定义文件
        if (beforeUploadId != null) {
            if (afterUploadId.longValue() != 0 && !beforeUploadId.equals(afterUploadId)) {
                custFileService.updateCustFileItemInfo(String.valueOf(afterUploadId), null);
                contractProtocolist.setCustomTemplateId(afterUploadId);
                contractProtocolist.setCustomTemplateName(custFileService.findOne(afterUploadId).getFileName());
                contractTempStampPlaceService.delAssociatedLocation(anId);
                contractProtocolist.setWhetherConvert("02");
                contractProtocolist.setCustomUpload("01");
                contractProtocolist.setProtocolName("自定义协议");
            }
        }
        // 之前已存自定义文件，现在删除自定义文件
        if (beforeUploadId != null) {
            if (afterUploadId.longValue() == 0) {
                contractProtocolist.setCustomTemplateId(0L);
                contractProtocolist.setCustomTemplateName("");
                contractProtocolist.setThumbnailBatchNo(0L);
                contractProtocolist.setWhetherConvert("");
                contractTempStampPlaceService.delAssociatedLocation(anId);
                contractProtocolist.setCustomUpload("02");
                contractProtocolist.setProtocolName("预定义协议");
            }
        }
        // 之前不存自定义文件，现在上传自定文件
        if (beforeUploadId == null) {
            if (afterUploadId.longValue() != 0) {
                custFileService.updateCustFileItemInfo(String.valueOf(afterUploadId), null);
                contractProtocolist.setCustomTemplateId(afterUploadId);
                contractProtocolist.setCustomTemplateName(custFileService.findOne(afterUploadId).getFileName());
                contractProtocolist.setCustomUpload("01");
                contractProtocolist.setProtocolName("自定义协议");
                contractProtocolist.setThumbnailBatchNo(updateChangeIntoPictures(afterUploadId));
                contractProtocolist.setWhetherConvert("02");
            }
        }
        // 根据协议清单重新编辑签署方信息
        if (contractSignatoryService.queryAllContractSignatory(anId).isEmpty()) {
            contractSignatoryService.addContractSignatory(anCommonNo, contractProtocolist.getRequestno(), anId);
        } else {
            contractSignatoryService.delAssociatedSignature(anId);
            contractSignatoryService.addContractSignatory(anCommonNo, contractProtocolist.getRequestno(), anId);
        }
        // 协议清单相关信息
        contractProtocolist.setStandardTypeId(BetterStringUtils.toLong(anParam.get("standardTypeId")));
        contractProtocolist.setOriginalTemplateId(BetterStringUtils.toLong(anParam.get("templateId")));
        contractProtocolist.setStandardTypeName(String.valueOf(anParam.get("standardTypeName")));
        if (anParam.get("signatoryTheme") != null) {
            contractProtocolist.setSignatoryTheme(String.valueOf(anParam.get("signatoryTheme")));
        }
        if (anParam.get("themeEndDate") != null) {
            contractProtocolist
                    .setThemeEndDate(BetterDateUtils.formatDispDate(String.valueOf(anParam.get("themeEndDate"))));
        }
        if (anParam.get("themeEndDate") != null) {
            contractProtocolist.setDescription(String.valueOf(anParam.get("description")));
        }
        String[] sourceStrArray = anCommonNo.split(",");
        // 根据签署方信息编号插入签署方式
        if (sourceStrArray.length == 1) {
            contractProtocolist.setSignatoryMode("一方签署");
        } else {
            contractProtocolist.setSignatoryMode("多方签署");
        }
        this.updateByPrimaryKey(contractProtocolist);
        return contractProtocolist;
    }

    /**
     * 
     * @Title: webQueryIntoPictures 
     * @Description: 查看PDF转略缩图
     * @param anContractProtocoId 协议清单编号
     * @return PDF转略缩图
     * @throws 
     * @author xuzx
     * @date 2017年11月3日 下午1:42:34
     */
    public String[] webQueryIntoPictures(final Long anContractProtocoId) {
        BTAssert.notNull(anContractProtocoId, "协议清单编号为空");
        final ContractProtocolist contractProtocolist = this.selectByPrimaryKey(anContractProtocoId);
        // 根据协议清单编号转为略缩图
        Long customTemplateId = contractProtocolist.getCustomTemplateId();
        CustFileItem fileItem = custFileService.findOne(customTemplateId);
        if ("02".equals(contractProtocolist.getWhetherConvert())) {
            contractProtocolist.setWhetherConvert("01");
            InputStream fis = dataStoreService.loadFromStore(customTemplateId);
            contractProtocolist.setThumbnailBatchNo(dataStoreService.savePdf2ImageStand(fis));
            this.updateByPrimaryKey(contractProtocolist);

        }
        // 查出略缩图批次号，根据批次号返回略缩图id
        List<CustFileItem> files = custFileService.findCustFiles(contractProtocolist.getThumbnailBatchNo());
        List<String> fileId = new ArrayList<String>();
        for (CustFileItem custFileItem : files) {
            fileId.add(String.valueOf(custFileItem.getId()));
        }
        int size = fileId.size();
        String[] arr = fileId.toArray(new String[size]);
        return arr;
    }

    /**
     * 
     * @Title: UpdateChangeIntoPictures 
     * @Description: 根据上传文件编号转为略缩图
     * @param 文件编号
     * @return 上传文件编号转为略缩图
     * @throws 
     * @author xuzx
     * @date 2017年11月3日 下午3:57:55
     */
    public Long updateChangeIntoPictures(final Long upLodeId) {
        InputStream fis = dataStoreService.loadFromStore(upLodeId);
        return dataStoreService.savePdf2ImageStand(fis);

    }

    /**
     * 
     * @Title: webSaveSignatureLocation 
     * @Description: 自定义协议插入签章位置
     * @param anParamMap 签章位置集合
     * @param anContractProtocoId 协议清单
     * @return 插入签章位置
     * @throws 
     * @author xuzx
     * @date 2017年11月5日 下午5:13:27
     */
    public int webSaveSignatureLocation(final Map<String, Object> anParamMap, final Long anContractProtocoId) {
        ContractProtocolist contractProtocolist = this.selectByPrimaryKey(anContractProtocoId);
        final String standardTypeName = contractProtocolist.getStandardTypeName();
        Map<String, Object> anMap = new HashMap<String, Object>(1);
        final CustOperatorInfo operator = UserUtils.getOperatorInfo();
        anMap.put("protocolListId", anContractProtocoId);
        int signatoryLeng = contractSignatoryService.queryCountContractSignatory(anContractProtocoId);
        contractTempStampPlaceService.saveCustomLocation(anParamMap, anContractProtocoId, standardTypeName,
                signatoryLeng);
        return signatoryLeng;

    }

    /**
     * 
     * @Title: queryAssociatedInformation 
     * @Description: 查询协议清单关联信息 
     * @param anContractProtocoId 协议清单编号
     * @return 查询协议清单关联信息 
     * @throws 
     * @author xuzx
     * @date 2017年11月6日 下午2:49:58
     */
    public ContractProtocolist queryAssociatedInformation(final Long anContractProtocoId) {
        ContractProtocolist contractProtocolist = this.selectByPrimaryKey(anContractProtocoId);
        contractProtocolist.setContractTemplateStampPlace(
                contractTempStampPlaceService.queryDetailContractSignatory(anContractProtocoId));
        if (contractTempStampPlaceService.queryDetailContractSignatory(anContractProtocoId).size() == 0) {
            contractProtocolist
                    .setContractSignatory(contractSignatoryService.queryAllContractSignatory(anContractProtocoId));
        }
        return contractProtocolist;

    }
}
